<template>
  <div class="login-container">
    <div class="login-box">
      <h2 class="login-title">中国移动智能客服</h2>
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
        <el-form-item prop="userId">
          <el-input
            v-model="loginForm.userId"
            placeholder="请输入账号"
            prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleLogin"
            :loading="loading"
            style="width: 100%"
          >
            登录
          </el-button>
        </el-form-item>
        <el-form-item style="text-align: right; margin-bottom: 0;">
          <el-button type="text" @click="handleForgotPassword">
            忘记密码？
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const loading = ref(false)
const loginFormRef = ref()

const loginForm = ref({
  userId: '',
  password: ''
})

const loginRules = {
  userId: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const handleLogin = () => {
  loginFormRef.value.validate((valid) => {
    if (!valid) return
    
    loading.value = true
    axios.post('/api/login', 
      new URLSearchParams({
        userId: loginForm.value.userId,
        password: loginForm.value.password
      }), {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      withCredentials: true  // 确保携带cookie
    })
      .then(response => {
        if (response.data?.code === 200) {
          ElMessage.success('登录成功')
          // 不需要前端存储用户信息，后端已通过session保存
          router.push('/chat')  // 直接跳转，后端拦截器会从session获取用户信息
        } else {
          ElMessage.error('登录失败：' + (response.data?.msg || '请检查账号密码'))
        }
      })
      .catch(error => {
        if (error.code === 'ERR_NETWORK') {
          ElMessage.error('无法连接到服务器，请检查网络连接或服务是否启动')
        } else {
          console.error('登录请求失败:', error)
          ElMessage.error('登录请求失败：' + error.message)
        }
      })
      .finally(() => {
        loading.value = false
      })
  })
}

const handleForgotPassword = () => {
  ElMessage.warning('请联系管理员重置密码')
}
axios.defaults.withCredentials = true; // 全局设置
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  color: #409eff;
}
</style>